import React, {Component} from 'react';
import axios from 'axios'
import PubSub from "pubsub-js";

class Index extends Component {
    search = async () => {
        const {keyWordElement: {value: keyWord}} = this
        PubSub.publish('updateListState', {
            isFirst: false,
            isLoading: true
        })
        // fetch(`https://api.github.com/search/users?q=${keyWord}`).then(
        //     response => {
        //         console.log('联系服务器成功')
        //         return response.json()
        //     },
        //     error => {
        //         console.log('联系服务器失败', error)
        //         return new Promise(() => {
        //         })    //返回初始化promise卡住 若无则会走下面的then
        //     }
        // ).then(
        //     response => {
        //         console.log(response)
        //         PubSub.publish('updateListState', {
        //             users: response.items,
        //             isLoading: false
        //         })
        //     },
        //     error => {
        //         PubSub.publish('updateListState', {
        //             isLoading: false,
        //             err: error.message
        //         })
        //     }).catch((error)=>{console.log(error)})
        // fetch(`https://api.github.com/search/users?q=${keyWord}`).then(
        //     response => {
        //         return response.json()
        //     }
        // ).then(
        //     response => {
        //         PubSub.publish('updateListState', {
        //             users: response.items,
        //             isLoading: false
        //         })
        //     })
        //     .catch((error) => {
        //         console.log(error)
        //     })
        try {
            const response = await fetch(`https://api.github.2com/search/users?q=${keyWord}`)
            const data = await response.json()
            PubSub.publish('updateListState', {
                users: data.items,
                isLoading: false
            })
        } catch (e) {
            PubSub.publish('updateListState', {
                isLoading: false,
                err: e.message
            })
        }
    }

    render() {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">搜索 Github 用户</h3>
                <div>
                    <input ref={c => this.keyWordElement = c} type="text" placeholder="输入关键词点击搜索"/>&nbsp;
                    <button onClick={this.search}>搜索</button>
                </div>
            </section>
        );
    }
}

export default Index;